package com.abo.yaas.webservice.utils;

import com.abo.yaas.domain.User;
import com.abo.yaas.webservice.exceptions.InvalidCredentialsException;
import com.abo.yaas.webservice.exceptions.WebServiceException;

/**
 * Utility class for authenticating users
 */
public class AuthenticationUtil {
    /**
     * Try to log in a user with the given user credentials
     * 
     * @param username
     *            Username of the user
     * @param password
     *            Password of the user
     * @return The authenticated user object
     * @throws InvalidCredentialsException
     *             Thrown if the crendentials are incorrect
     */
    public static User authenticate(String username, String password)
            throws InvalidCredentialsException {
        if (username == null || password == null) {
            throw new InvalidCredentialsException();
        }

        final User user = UserFacade.getUserByLogin(username);

        if (user == null) {
            throw new WebServiceException(
                    "No records found for such login and password!");
        }

        if (!PasswordUtil.verifyPassword(user, password)) {
            throw new WebServiceException("Passwords do not match!");
        }

        user.setPassword(password);
        return user;
    }
}
